import numpy as np
import os
from keras.models import load_model
import librosa


# 提取 mfcc 参数
def wav2mfcc(path, max_pad_size=11):
    y, sr = librosa.load(path=path, sr=None, mono=False)
    # y = y[::3]
    audio_mac = librosa.feature.mfcc(y=y, sr=16000)
    y_shape = audio_mac.shape[1]
    if y_shape < max_pad_size:
        pad_size = max_pad_size - y_shape
        audio_mac = np.pad(audio_mac, ((0, 0), (0, pad_size)), mode='constant')
    else:
        audio_mac = audio_mac[:, :max_pad_size]
    return audio_mac


if __name__ == '__main__':
    # 构建模型
    model = load_model('./model/asr_model_weights11.h5') # 加载训练模型
    # for j in range(24):
    # print(np.shape(compute_mfcc("my_test_site_data//record41_go.wav")))
    # for j in range(41,49):
    #     wavs.append(get_wav_mfcc("my_test_site_data//record"+str(j)+"_go.wav"))
    label = ["down","go","left","right","stop","up"]
    all_result=[]
    for k in label:
        wavs = []
        score=0
        error_index=[]
        path='./data/test_{}/'.format(k)#*******文件路径
        # path = 'D:\\voice\\test_data\\test_{}\\'.format(k)
        files = os.listdir(path)
        for j,_ in enumerate(files):
            wavs.append(wav2mfcc(path + _))
            X=np.array(wavs)
            # print(X.shape)
            x=X.reshape((-1,220))
            result=model.predict(x,batch_size=128)[0]# 识别出第一张图的结果，多张图的时候，把后面的[0] 去掉，返回的就是多张图结果
            # print(np.shape(result))
            # print("识别结果",result)
            # #  因为在训练的时候，标签集的名字 为：  0：seven   1：stop    0 和 1 是下标
            name = ["down","go","left","right","stop","up"] # 创建一个跟训练时一样的标签集  ,["down","go","left","right","stop","up"]
            ind=0 # 结果中最大的一个数
            print(result)#result[0],result[1],result[2],result[3],result[4],result[5]
            for i in range(len(result)):
                if result[i] > result[ind]:
                    ind=i
            print("识别的语音结果是：",name[ind])
            if (name[ind]==k):
                score+=1
            else:
                error_index.append(j)
        print("正确率：",score)
        print("错误的下标：",error_index)
        all_result.append(score)
    for i in range(len(label)):
        print('{}:{}'.format(label[i],all_result[i]))